﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CS_Util {
    /// <summary>
    /// 本地log
    /// </summary>
    public class C_LogTxtSave {
        public string onlyName;
        long msgIndex, fileIndex;
        public string prefixPath { get; private set; }
        string fileName, _saveFullPath;
        public string o_saveFullPath { get; private set; }
        static List<C_LogTxtSave> o_localLogs = new List<C_LogTxtSave>();
        public C_LogTxtSave(string onlyName, string prefixPath = null) {
            if (string.IsNullOrEmpty(prefixPath)) {
                prefixPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                prefixPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/logList";
            }
            o_localLogs.Add(this);
            onlyName = onlyName.Replace("\\","");
            onlyName = onlyName.Replace("/","");
            onlyName = onlyName.Replace(":","");
            onlyName = onlyName.Replace("?","");
            onlyName = onlyName.Replace("*","");
            onlyName = onlyName.Replace("\"","");
            onlyName = onlyName.Replace("<", "");
            onlyName = onlyName.Replace(">", "");
            this.onlyName = DateTime.Now.ToString("HH.mm.ss")+onlyName;
            this.prefixPath = prefixPath;
            fileName = string.Format("{0}/{1}/{2}", onlyName, DateTime.Now.ToString("yyyy年MM月dd号"), DateTime.Now.ToString("HH点mm分ss秒")); 
            S_CreateFile();
        }
        int maxMsgNumberLimit = 3000;
        void S_CreateFile() {
            fileIndex = msgIndex / maxMsgNumberLimit;
            _saveFullPath = string.Format("{0}/{1}_{2}.html", prefixPath, fileName, fileIndex);
            string dd = Path.GetDirectoryName(_saveFullPath);
            if (Directory.Exists(dd) == false) {
                Directory.CreateDirectory(dd);
            }
            StringBuilder ssb = new StringBuilder();
            ssb.AppendFormat("<html>\r\n<title>{0}</title>\r\n<body bgcolor='#222222'>\r\n", onlyName);
            string html_01 =
@"<script type='text/javascript'>
  window.onload = function(){
        var fonts = document.getElementsByTagName('font');
        for (var i = 0, j = fonts.length; i < j; i++) {
            if (fonts[i].color == '#006060') {
                fonts[i].style.display = 'none';
                var br = fonts[i].nextElementSibling;
                if (br.nodeName != 'br') br.style.display = 'none';
            } else {
                fonts[i].onclick = function(){
                    var next = this.nextElementSibling;
                    if (next.nodeName != 'font') next = next.nextElementSibling;
                    if (next.style.display == 'none')
                        next.style.display = 'block';
                    else
                        next.style.display = 'none';
                }
            }
        }
    }
</script> 
";
            ssb.Append(html_01);
            ssb.AppendFormat("<font size = '3' color = '#00bb88' > {0} </font><br/>\r\n", fileName);
            ssb.AppendFormat("<br/>");
            File.WriteAllText(_saveFullPath, ssb.ToString(), Encoding.UTF8);
        }

        public void S_AddLog(byte type, string tag, string currentTime,string condition, string stackTrace) {
            m_Log mm = new m_Log() {
                msgType = type,
                msgIndex = msgIndex++,
                log = condition,
                stackTrace = stackTrace
            };
            mm.time = currentTime + "";
            if (fileIndex != msgIndex / maxMsgNumberLimit) {
                S_CreateFile();
            }
            logList.Add(mm);
            if (logList.Count > 300) {
                SaveData();
            }
        }
        List<m_Log> logList = new List<m_Log>();
        public static void S_SaveData() {
            for(int i=0;i< o_localLogs.Count; i++) {
                o_localLogs[i].SaveData();
                Console.WriteLine("log保存成功: {0}", o_localLogs[i].o_saveFullPath);
            }
        }
        public void S_Clear() {
            SaveData();
            o_localLogs.Remove(this);
        }
        void SaveData() {
            StringBuilder ssb = new StringBuilder();
            for (int i = 0; i < logList.Count; i++) {
                string log = logList[i].log.Replace("\n", "<br>&ensp;&ensp;&ensp;&ensp;");
                string color = null;
                log = log.S_GetLogColor(out color);
                switch (logList[i].msgType) {
                    case 0://Error
                        if(color==null) color = "990022";
                        ssb.AppendFormat("\t<font size = '1' color = '#{0}' style='background-color:#220000' > {1}>-  {2}</font><br/>\r\n", color, logList[i].msgIndex, log);
                        break;
                    case 1://Assert
                        if (color == null) color = "9999bb";
                        ssb.AppendFormat("\t<font size = '1' color = '#{0}' > {1}>-  {2}</font><br/>\r\n", color, logList[i].msgIndex, log);
                        break;
                    case 2://Warning
                        if (color == null) color = "999900";
                        ssb.AppendFormat("\t<font size = '1' color = '#{0}' style='background-color:#444400' > {1}>-  {2}</font><br/>\r\n", color, logList[i].msgIndex, log);
                        break;
                    case 3://Log
                        if (color == null) color = "609940";
                        ssb.AppendFormat("\t<font size = '1' color = '#{0}' > {1}>-  {2}</font><br/>\r\n", color, logList[i].msgIndex, log);
                        break;
                    case 4://Exception
                        if (color == null) color = "ff00ff";
                        ssb.AppendFormat("\t<font size = '1' color = '#{0}' style='background-color:#880088' > {1}>-  {2}</font><br/>\r\n", color, logList[i].msgIndex, log);
                        break;
                }
                ssb.AppendFormat("\t<font size = '1' color = '#006060' > {0}===>{1}</font><br/>\r\n", logList[i].time, logList[i].stackTrace.Replace("\n","<br>"));
            }
            //ssb.AppendFormat("</body>\r\n</html>");
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(_saveFullPath, true)) {
                file.Write(ssb.ToString());//直接追加文件末尾，不换行
            }
            //C_Log.LogError("S_SaveData---------------------" + logList.Count);
            logList.Clear();
        }
        struct m_Log {
            public byte msgType;
            public long msgIndex;
            public string log, stackTrace, time;
        }
    }
}
